package com.yaoxun.quartz.job;

import java.util.Date;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import com.yaoxun.quartz.domain.entity.ScheduleJob;
import com.yaoxun.quartz.domain.entity.ScheduleJobLog;
import com.yaoxun.quartz.service.ScheduleJobLogService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@DisallowConcurrentExecution //配置防止并发执行
@PersistJobDataAfterExecution 
public class CronJob implements Job {

	@Autowired
	private ApplicationContext applicationContext;
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get(ScheduleJob.PARAMS_NAME);
		ScheduleJobLogService logService = applicationContext.getBean(ScheduleJobLogService.class);
		//创建schedule 日志
		ScheduleJobLog scheduleJobLog = new ScheduleJobLog();
		scheduleJobLog.setJobId(scheduleJob.getJobId());
		scheduleJobLog.setBeanName(scheduleJob.getBeanName());
		scheduleJobLog.setParams(scheduleJob.getParams());
		scheduleJobLog.setCreateTime(new Date());
		//任务开始时间
		long startTime = System.currentTimeMillis();
		try {
			log.debug("任务准备执行，任务ID：" + scheduleJob.getJobId());
			JobRunner jobRunner = applicationContext.getBean(scheduleJob.getBeanName(), JobRunner.class);
			jobRunner.run(scheduleJob.getParams());
			scheduleJobLog.setRunStatus(ScheduleJobLog.RUN_STATE_SUCCESS);
		} catch (Exception e) {
			log.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);
			scheduleJobLog.setErrorInfo(subErrorInfo(e));
			scheduleJobLog.setRunStatus(ScheduleJobLog.RUN_STATE_FAIL);
		} finally {
			//运行时长
			long times = System.currentTimeMillis() - startTime;
			scheduleJobLog.setTimes(times);
			logService.save(scheduleJobLog);
		}
		
	}
	
	private String subErrorInfo(Exception e) {
		if(e.getMessage().length() > 2000) {
			return e.getMessage().substring(0, 2000);
		}
		return e.getMessage();
	}
	
}
